package algorithm;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.List;

import javax.swing.ImageIcon;

public class TextureChanger {
	
	private BufferedImage picture;
	private List<Mask> masks;
	private Color mascara;
	
	
	
	public TextureChanger(BufferedImage texture, List<Mask> masks) {
		super();

		this.picture = texture;
		this.masks = masks;
		
		
	}



	public BufferedImage getTextureChanged()
	{
		BufferedImage bdest = new BufferedImage(picture.getWidth(), picture.getHeight(), picture.getType());
		Graphics2D g = bdest.createGraphics();
		g.drawRenderedImage(picture, new AffineTransform());
		
		long start= System.currentTimeMillis();
		
		for (int i = 0; i < masks.size(); i++) {
			bdest = changeTexture(picture,masks.get(i),g, bdest);
		}
		g.dispose();
		
		long elapsedTime = System.currentTimeMillis() - start;
	    System.out.println("time: "+elapsedTime);
		return bdest;
	}
	
	private BufferedImage changeTexture(BufferedImage picture,
			Mask mask, Graphics2D g, BufferedImage bdest) {

	    // 1,141 seg
		
	    
		for(int i= (int) mask.getOrigin().getY(); i < mask.getOriginInf().getY();i++)
		{
			for(int j= (int) mask.getOrigin().getX(); j < mask.getOriginInf().getX();j++)
			{
				
				int a = picture.getRGB(j, i);
				
				
				if (mask.inArea(j, i))
				{
					
					int color = a & mascara.getRGB();
					g.setColor(new Color(color));
					g.fillRect(j, i, 1, 1);
					
				}
				else
					bdest.setRGB(j, i, a);
				
				}	
			
			}
		
		
		return bdest;
	
	}

	
	

	public BufferedImage getTexture() {
		return picture;
	}
	public void setDisplay(BufferedImage texture) {
		this.picture = texture;
	}

	
	public ImageIcon createImageIcon(String path) {
		java.net.URL imageURL = this.getClass().getResource(path);

		if (imageURL == null) {
			System.err.println("Resource not found: " + path);
			return null;
		} else {
			return new ImageIcon(imageURL);
		}
	}

	public Color getMascara() {
		return mascara;
	}

	public void setMascara(Color mascara) {
		this.mascara = mascara;
	}
}
